package com.ag.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.springframework.stereotype.Service;

import com.ag.admin.dao.TbLoginRecordDAO;
import com.ag.admin.dao.TbUserDAO;
import com.ag.admin.service.ILoginOutService;
import com.ag.admin.utils.UserSession;
import com.ag.admin.utils.UserUtil;
import com.ag.bean.TbLoginRecord;
import com.ag.bean.TbPermission;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserRole;
import com.ag.common.IDUtil;
import com.ag.common.IIDService;

/**
 * 系统用户登入登出业务逻辑服务类
 * 
 * @author 黎肇明
 * 
 */
@Service("LoginOutServiceImpl")
public class LoginOutServiceImpl implements ILoginOutService {

	@Resource(name = "LZMTbUserDAO")
	private TbUserDAO userDAO;
	@Resource(name = "LZMTbLoginRecordDAO")
	private TbLoginRecordDAO lrDAO;
	@Resource(name = "iDServiceImpl")
	private IIDService idServiceImpl;
	@Resource(name = "CheckUserServiceImpl")
	private CheckUserServiceImpl checkUserServiceImpl;

	/**
	 * 检查用户登录方法，转入：用户名和密码，传出：登录响应码
	 */
	@Override
	public String checkLogin(String UId, String UPassword, String verifyCode,
			Map<String, Object> session, ServletContext context, String clientIP) {
		String realCode = (String) session.get(UserUtil.VERIFY_CODE);
		if (verifyCode.length() > 0 && verifyCode != null
				&& realCode.equals(verifyCode)) {
			if (UId.length() > 0 && UId != null && UPassword.length() > 0
					&& UPassword != null) {
				// // System.out.println(UId);
				// String hsql =
				// "select u from TbUser u join fetch u.tbUserRoles ur join fetch ur.tbRole"
				// +
				// " join fetch u.tbUserDepts ud join fetch ud.tbDeptType where u.UId = ?";
				// TbUser user = (TbUser) userDAO.find(hsql, UId).get(0);
				// /*
				// * System.out.println(UId); Set<TbUserRole> rSet =
				// * user.getTbUserRoles(); for (Iterator<TbUserRole> iterator =
				// * rSet.iterator(); iterator .hasNext();) { //
				// TbRolePermission
				// * r=(TbRolePermission)iterator; // System.out.println(r); //
				// * System.out.println(++i);
				// * System.out.println(iterator.next().getTbRole().getRName());
				// }
				// */
				// // System.out.println(user);
				// MD5withSalt md5 = new MD5withSalt(UId, "MD5");
				// if (user == null
				// || !md5.isPasswordValid(user.getUPassword(), UPassword)) {
				// return UserUtil.LOGIN_FAIL;// 登录失败
				// } else if (UserUtil.EXPIRED.equals(user.getB())) {
				// return UserUtil.EXPIRED;// 账户过期
				// } else if (UserUtil.FREEZE.equals(user.getB())) {
				// return UserUtil.FREEZE;// 账户冻结
				// } else {
				// // System.out.println(user);
				// user.setULoginTime(new Date());
				// user.setC(clientIP);
				// userDAO.attachDirty(user);
				// handleUserSession(user, session, context);// 处理用户Session
				// loginRecord(user);// 记录用户登录日志
				// return UserUtil.LOGIN_SUCC;// 验证成功
				// }
				if (checkUserServiceImpl.checkUser(UId, UPassword)) {
					String hsql = "select u from TbUser u join fetch u.tbUserRoles ur join fetch ur.tbRole"
							+ " join fetch u.tbUserDepts ud join fetch ud.tbDeptType where u.UId = ?";
					TbUser user = (TbUser) userDAO.find(hsql, UId).get(0);
					user.setULoginTime(new Date());
					user.setC(clientIP);
					userDAO.attachDirty(user);
					handleUserSession(user, session, context);// 处理用户Session
					loginRecord(user);// 记录用户登录日志
					return UserUtil.LOGIN_SUCC;// 验证成功
				} else {
					return UserUtil.LOGIN_FAIL;// 登录失败
				}
			} else {
				return UserUtil.NULL_VALUE;// 用户名或密码为空
			}
		}
		return UserUtil.VERIFY_EERROR;// 验证码错误
	}

	/**
	 * 记录用户登录日志
	 * 
	 * @param tbUser
	 */
	private void loginRecord(TbUser tbUser) {
		TbLoginRecord lr = new TbLoginRecord();
		String id = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
				+ idServiceImpl.findTablePK(IDUtil.TB_LOGIN_RECORD);
		lr.setLrId(id);
		lr.setLrLoginTime(new Date());
		lr.setTbUser(tbUser);
		lr.setA(IDUtil.PRESERVE);
		lr.setC(tbUser.getC());
		lrDAO.save(lr);
	}

	/**
	 * 处理用户Session
	 * 
	 * @param tbUser
	 * @param session
	 */
	private void handleUserSession(TbUser tbUser, Map<String, Object> session,
			ServletContext context) {
		Map<String, Map<String, TbPermission>> initMap = (Map<String, Map<String, TbPermission>>) context
				.getAttribute(UserUtil.ROLE_AUTHORITIES);
		Map<String, Map<String, TbPermission>> roleMap = new HashMap<String, Map<String, TbPermission>>();
		roleMap.putAll(initMap);
		List<String> roleList = findAllRoleByUserID(tbUser.getUId());// 调用内部方法，通过用户ID找出用户所有角色
		Iterator<String> iterator = roleMap.keySet().iterator();
		while (iterator.hasNext()) {
			String mapKey = iterator.next();
			if (!roleList.contains(mapKey)) {
				iterator.remove();
			}
		}
		UserSession userSession = new UserSession();
		userSession.setTbUser(tbUser);
		userSession.setUserPemission(roleMap);
		session.put(UserUtil.USER_SESSION, userSession);
		session.remove(UserUtil.VERIFY_CODE);
	}

	/**
	 * 通过用户ID找出用户所有角色
	 * 
	 * @param UId
	 *            用户ID
	 * @return 角色ID列表
	 */
	public List<String> findAllRoleByUserID(String UId) {
		StringBuilder sb = new StringBuilder();
		sb
				.append("select r.RId from TbRole r join r.tbUserRoles ur join ur.tbUser u where u.UId = '");
		sb.append(UId);
		sb.append("'");
		return userDAO.find(sb.toString());
	}

	/**
	 * 通过用户ID找出用户所有角色
	 * 
	 * @param UId
	 *            用户ID
	 * @return 角色ID列表
	 */
	public List<TbUserRole> findRoleEventByUserID(String UId) {
		// StringBuilder sb = new StringBuilder();
		// sb
		// .append("from TbRole r join r.tbUserRoles ur join ur.tbUser u where u.UId = '");
		// sb.append(UId);
		// sb.append("'");
		String queryString = "from TbUserRole ur where ur.tbUser.UId = ?";
		return userDAO.find(queryString, UId);
	}
}
